package org.linlinjava.litemall.event.handler;

import com.mzwise.tunnel.wx.builder.TextBuilder;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.linlinjava.litemall.db.domain.LitemallCouponUser;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.LitemallCouponUserService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.util.CouponConstant;
import org.linlinjava.litemall.db.util.CouponUserConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.EventType;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class GetCardHandler extends AbstractHandler {

    @Autowired
    private LitemallUserService userService;

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private LitemallCouponUserService litemallCouponUserService;

    @Autowired
    private LitemallUserService litemallUserService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {
        String msg = String.format("type:%s, event:%s, key:%s",
            wxMessage.getMsgType(), wxMessage.getEvent(),
            wxMessage.getEventKey());
        String fromUser = wxMessage.getFromUser();
        String unionId = wxMessage.getUnionId();
        this.logger.info("用户领取卡卷事件");
        this.logger.info("用户openid: " + fromUser);
        this.logger.info("用户unionId: " + unionId);
        Integer isGiveByFriend = wxMessage.getIsGiveByFriend();
        if (isGiveByFriend.equals(0)) { // 普通领取事件
            // 好像没嘛可处理的
        } else { // 赠送卡卷领取事件
            if (unionId==null) { // 目前发现转增后领取获取不到unionId
                try {
                    WxMpUser wxMpUser = wxMpService.getUserService().userInfo(fromUser, "zh_CN");
                    this.logger.info("用户unionId: " + wxMpUser.getUnionId());
                    unionId = wxMpUser.getUnionId();
                } catch (WxErrorException e) {
                    this.logger.info("获取用户信息失败");
                    e.printStackTrace();
                }
            }
            String oldUserCardCode = wxMessage.getOldUserCardCode(); //老 code
            String userCardCode = wxMessage.getUserCardCode(); // 新 code
            LitemallCouponUser couponUser = litemallCouponUserService.findByWxCode(oldUserCardCode);
            if (couponUser.getStatus() != CouponUserConstant.STATUS_GIFTING) {
                return new TextBuilder().build("领取卡卷失败，无法正常在商城使用", wxMessage, weixinService);
            }
            // 根据unionId查询用户
            LitemallUser user = litemallUserService.queryByUid(unionId);
            if (user != null) {
                couponUser.setStatus(CouponUserConstant.STATUS_USABLE);
                couponUser.setWxCode(userCardCode);
                couponUser.setUserId(user.getId());
                litemallCouponUserService.update(couponUser);
            }
        }
        return new TextBuilder().build("恭喜您，领取卡卷成功", wxMessage, weixinService);
    }

}
